<?php
class Blog extends AppModel {
		
	var $hasMany = array(
		'Link'
	);
	
	var $validate=array(
		'key'=>array(
			'rule'=>'isunique',
			'message'=>'El blog ya esta en la base'
		)
	);
	
		            
    function getBlogData($url,$html){
    	
    	$blog=array(
    		'type'=>'normal',
    		'rss'=>$this->getShortestValFromExp('/<link[^>]+text\/xml[^>]+href=[^>]+>/i','/href="([^"]+)"/i',$html),
			'atom'=>$this->getShortestValFromExp('/<link[^>]+application\/atom\+xml[^>]+>/i','/href="([^"]+)"/i',$html),
			'rss2'=>$this->getShortestValFromExp('/<link[^>]+application\/rss\+xml[^>]+>/i','/href="([^"]+)"/i',$html)
    	);
    	
		if($blog['rss']||$blog['rss2']||$blog['atom']) $blog['type']='blog';
		
	    // Last try to find a rss
		if($blog['type']!='blog' && preg_match('/<a[^>]+href="(http[^>]+\.rdf)"/i', $html, $matches2)) {
				$blog['rss']=$matches2[1];
				$blog['type']='blog';
		}
		
		//finalmente intentamos encontrar la direccion del blog
		$blog['url']=$this->getDomain($url,$blog);
		$blog['key']=md5($blog['url']);
		
		$this->set($blog);
		if(!$id=$this->field('id',array('key'=>$blog['key']))){
			$this->save();
			return $this->id;	
		}

		return $id;
    }  
    
	function getShortestString(array $strArray){
    	$shortest=false;
		foreach ($strArray as $s){
			if (!$shortest || strlen($s) < strlen($shortest)) {
				$shortest=$s;
			}
		}
    	return $shortest;
    }
    
    
    //TODO REFACTOR!
    function getDomain($url,$blog){
    	// Try to find the base url
		$feeds = array_diff(array($blog['rss'], $blog['rss2'], $blog['atom']),array(''));
		
		$path='';
		$url_url = parse_url($url);
		
		$url_url['path'] = isset($url_url['path']) ? preg_replace('/\/$/', '', $url_url['path']) :'';
		$host = $url_url['host'];
		if($blog['type']=='blog') {
			$host_quoted = preg_quote($host);
			$rss_found = false;
			foreach ($feeds as $feed) {
								
				$rss_url = parse_url($feed);
				if(!isset($rss_url['host']))$rss_url['host']='';
				
				$rss_quoted = preg_quote($rss_url['host']);
				if ($host == $rss_url['host']) {
					// Same hostname, keep it
					$rss_found = true;
					break;
				} elseif (preg_match("/^www\.$rss_quoted$/", $host)) {
					// hostname from url is the shortest
					$rss_found = true;
					break;
				} elseif (preg_match("/^www\.$host_quoted$/", $rss_url['host']))  {
					// RSS hostname is the shortest
					$host = $rss_url['host'];
					$rss_found = true;
					break;
				}
			}
			if ($rss_found) {
				$rss_url['path'] = preg_replace('/(index\.(.){3,4})*\/+$/', '', $rss_url['path']);
				if (preg_match('/\//', $rss_url['path'])) {  // Still has at least a /, that is a "sub blog"
					$dir_path = dirname($rss_url['path']);
					
					$i=0;
					foreach(str_split($url_url['path']) as $c) {
						if($c != substr($dir_path, 0, $i) ) {
							break;
						}
						$path = substr($dir_path, 0, $i);
						$i++;					
					}
					
				}
			}
		}
		$path = preg_replace('/(index\.(.){3,4})*\/+$/', '', $path);
		$scheme=empty($url_url['scheme']) ? "http" : $url_url['scheme'];
		$url=$scheme.'://'.strtolower($host).$path;
    	    	
    	return $url;		
    }
    
	function getShortestValFromExp($match,$secondMatch=null,$html){
    	$value=false;
    	
		if(preg_match_all($match, $html, $matches)) {
			$candidates=array();
			foreach ($matches[0] as $m){
				if($secondMatch){
					if(preg_match($secondMatch, $m, $matches2)) {
						array_push($candidates,$matches2[1]);
					}
				}else{
					array_push($candidates,$m);
				}
			}
			$value=$this->getShortestString($candidates);
		}
    	
		return ($value) ? $value : '';
    }	
	
}
?>